package com.demo.practiceui.views.chart;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PointF;
import android.util.AttributeSet;
import android.view.View;

import androidx.annotation.Nullable;

import java.util.ArrayList;
import java.util.List;

/**
 * 雷达图（蜘蛛网图）
 * 核心知识点：
 * 1. Path - 绘制多边形
 * 2. 极坐标转直角坐标 - 三角函数应用
 * 3. 多层网格绘制
 * 4. 数据点连线
 */
public class RadarChartView extends View {

    // 数据
    private float[] data = {80, 70, 90, 60, 85};  // 各维度数据（0-100）
    private String[] labels = {"攻击", "防御", "速度", "技能", "体力"};

    // 画笔
    private Paint gridPaint;           // 网格画笔
    private Paint dataPaint;           // 数据区域画笔
    private Paint dataLinePaint;       // 数据边线画笔
    private Paint textPaint;           // 文字画笔

    // 尺寸
    private int width;
    private int height;
    private float centerX;
    private float centerY;
    private float radius;

    // 网格层数
    private int gridLayers = 5;
    private int dimension;  // 维度数（几边形）

    private Path gridPath;
    private Path dataPath;
    private List<PointF> dataPoints;

    public RadarChartView(Context context) {
        this(context, null);
    }

    public RadarChartView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public RadarChartView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        dimension = data.length;

        // 网格画笔
        gridPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        gridPaint.setColor(Color.parseColor("#CCCCCC"));
        gridPaint.setStyle(Paint.Style.STROKE);
        gridPaint.setStrokeWidth(2f);

        // 数据区域画笔
        dataPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        dataPaint.setColor(Color.parseColor("#804CAF50"));  // 半透明绿色
        dataPaint.setStyle(Paint.Style.FILL);

        // 数据边线画笔
        dataLinePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        dataLinePaint.setColor(Color.parseColor("#4CAF50"));
        dataLinePaint.setStyle(Paint.Style.STROKE);
        dataLinePaint.setStrokeWidth(4f);

        // 文字画笔
        textPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        textPaint.setColor(Color.parseColor("#333333"));
        textPaint.setTextSize(32f);
        textPaint.setTextAlign(Paint.Align.CENTER);

        gridPath = new Path();
        dataPath = new Path();
        dataPoints = new ArrayList<>();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int width = MeasureSpec.getSize(widthMeasureSpec);
        int height = MeasureSpec.getSize(heightMeasureSpec);
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);

        if (widthMode == MeasureSpec.AT_MOST) {
            width = 700;
        }
        if (heightMode == MeasureSpec.AT_MOST) {
            height = 700;
        }
        setMeasuredDimension(width, height);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        width = w;
        height = h;
        centerX = width / 2f;
        centerY = height / 2f;
        radius = Math.min(width, height) / 2f - 150;  // 留空间给标签
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        // 1. 绘制网格
        drawGrid(canvas);

        // 2. 绘制从中心到各顶点的连线
        drawAxisLines(canvas);

        // 3. 绘制数据区域
        drawDataArea(canvas);

        // 4. 绘制数据点
        drawDataPoints(canvas);

        // 5. 绘制标签
        drawLabels(canvas);
    }

    /**
     * 绘制多层网格
     */
    private void drawGrid(Canvas canvas) {
        for (int layer = 1; layer <= gridLayers; layer++) {
            float layerRadius = radius * layer / gridLayers;
            gridPath.reset();

            for (int i = 0; i < dimension; i++) {
                // 计算每个顶点的角度（从顶部开始，顺时针）
                float angle = (float) (Math.PI / 2 - (2 * Math.PI * i / dimension));
                float x = centerX + layerRadius * (float) Math.cos(angle);
                float y = centerY - layerRadius * (float) Math.sin(angle);

                if (i == 0) {
                    gridPath.moveTo(x, y);
                } else {
                    gridPath.lineTo(x, y);
                }
            }
            gridPath.close();
            canvas.drawPath(gridPath, gridPaint);
        }
    }

    /**
     * 绘制从中心到各顶点的连线
     */
    private void drawAxisLines(Canvas canvas) {
        for (int i = 0; i < dimension; i++) {
            float angle = (float) (Math.PI / 2 - (2 * Math.PI * i / dimension));
            float x = centerX + radius * (float) Math.cos(angle);
            float y = centerY - radius * (float) Math.sin(angle);

            canvas.drawLine(centerX, centerY, x, y, gridPaint);
        }
    }

    /**
     * 绘制数据区域
     */
    private void drawDataArea(Canvas canvas) {
        dataPath.reset();
        dataPoints.clear();

        for (int i = 0; i < dimension; i++) {
            // 计算数据点位置
            float angle = (float) (Math.PI / 2 - (2 * Math.PI * i / dimension));
            float dataRadius = radius * (data[i] / 100f);  // 数据归一化到半径
            float x = centerX + dataRadius * (float) Math.cos(angle);
            float y = centerY - dataRadius * (float) Math.sin(angle);

            dataPoints.add(new PointF(x, y));

            if (i == 0) {
                dataPath.moveTo(x, y);
            } else {
                dataPath.lineTo(x, y);
            }
        }
        dataPath.close();

        // 绘制填充区域
        canvas.drawPath(dataPath, dataPaint);

        // 绘制边线
        canvas.drawPath(dataPath, dataLinePaint);
    }

    /**
     * 绘制数据点
     */
    private void drawDataPoints(Canvas canvas) {
        Paint pointPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        pointPaint.setColor(Color.parseColor("#4CAF50"));
        pointPaint.setStyle(Paint.Style.FILL);

        for (PointF point : dataPoints) {
            canvas.drawCircle(point.x, point.y, 8, pointPaint);
        }
    }

    /**
     * 绘制标签
     */
    private void drawLabels(Canvas canvas) {
        for (int i = 0; i < dimension; i++) {
            float angle = (float) (Math.PI / 2 - (2 * Math.PI * i / dimension));
            float labelRadius = radius + 60;  // 标签在网格外侧
            float x = centerX + labelRadius * (float) Math.cos(angle);
            float y = centerY - labelRadius * (float) Math.sin(angle) + 10;

            // 绘制标签文字
            textPaint.setTextAlign(Paint.Align.CENTER);
            canvas.drawText(labels[i], x, y, textPaint);

            // 绘制数值
            textPaint.setTextSize(28f);
            textPaint.setColor(Color.parseColor("#666666"));
            canvas.drawText(String.format("%.0f", data[i]), x, y + 35, textPaint);

            // 恢复文字设置
            textPaint.setTextSize(32f);
            textPaint.setColor(Color.parseColor("#333333"));
        }
    }

    /**
     * 设置数据
     */
    public void setData(float[] data, String[] labels) {
        this.data = data;
        this.labels = labels;
        this.dimension = data.length;
        invalidate();
    }
}

